<template>
  <!-- 
      CURD 增删查改
      不需制作炫酷的交互，只是关注数据逻辑处理
     -->
  <div class="user-manager">
    <div class="query-form">
      <el-form
        :inline="true"
        :model="user"
        class="demo-form-inline"
        style="display: flex"
      >
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用户Id" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="user.state" placeholder="状态">
            <el-option label="所有" :value="0" />
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="2" />
            <el-option label="试用期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="resect">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="userCreate">新增</el-button>
        <el-button type="danger" @click="deleteAll">批量删除</el-button>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        ></el-table-column>
        <el-table-column width="160">
          <template #default="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="delteUser(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="showMadol" title="新增用户">
      <el-form :model="form" ref="dialogForm" :rules="rules">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="form.userEmail" autocomplete="off" />
        </el-form-item>
        <el-form-item label="号码" prop="userPhone">
          <el-input v-model="form.mobile" autocomplete="off" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="form.job" autocomplete="off" />
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="状态">
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="2" />
            <el-option label="试用期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList" style="width: 100%">
          <el-select
            v-model="form.roleList"
            multiple
            placeholder="选择用户角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleList"
              :key="item._id"
              :label="item.roleName"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择部门" style="width: 100%">
          <el-cascader
            :options="deptList"
            v-model="form.deptId"
            style="width: 100%"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            placeholder="请选择你的部门"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>
    <div class="example-pagination-block">
      <el-pagination
        layout="prev, pager, next"
        :total="50"
        @click="changepage"
      />
    </div>
  </div>
</template>

<script setup>
import api from '../api';
import { ref, reactive, nextTick, toRaw } from 'vue';
import utils from '../utils/utils';
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request';

// 分页
const changepage = () => {

}


// 定义一个用户行为初始化
const action = ref('add')
// 定义校验规则
const rules = reactive({
  userName: {
    required: true,
    message: '请输入用户名',
    reigger: 'blur'
  },
  userEmail: {
    required: true,
    message: '请输入邮箱',
    reigger: 'blur'
  },
  userPhone: [
    {
      pattern: /1[3-9]\d{9}/,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ]
});
// 定义dialogForm节点
const dialogForm = ref(null);
// 定义角色列表
const roleList = ref([]);
// 定义部门列表
const deptList = ref([]);
// 定义新增模块用户
const form = reactive({
  state: '',

});
// 定义弹窗
const showMadol = ref(false);
// 定义动态表格--格式
const columns = reactive([
  {
    label: '用户ID',
    prop: 'userId'
  },
  {
    label: '用户名',
    prop: 'userName'
  },
  {
    label: '用户邮箱',
    prop: 'userEmail'
  },
  {
    label: '用户角色',
    prop: 'role',
    formatter (row, column, value) {
      return {
        0: '管理员',
        1: '普通用户'
      }[value];
    }
  },
  {
    label: '用户状态',
    prop: 'state',
    formatter (row, column, value) {
      return {
        1: '在职',
        2: '离职',
        3: '试用期'
      }[value];
    }
  },
  {
    label: '注册时间',
    prop: 'createTime',
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    }
  },
  {
    label: '最后登陆时间',
    prop: 'lastLoginTime',
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    }
  }
]);
// 定义初始化用户分类
const user = reactive({
  state: ''
});
// 定义初始化的分页设置
const pager = reactive({
  pageNum: 1,
  pageSize: 10
});
// 定义用户列表
const userList = ref([]);
// 获取用户列表
const getUserList = async () => {
  let params = { ...user, ...pager };
  let { list, page } = await api.getUserList(params);
  userList.value = list;
  console.log(userList.value);
};
// 获取角色列表
const getRolesList = async () => {
  roleList.value = await api.getRolesList();
};
// 获取部门列表
const getdeptList = async () => {
  deptList.value = await api.getdeptList();
};
// 管理页面数据初始化请求
getRolesList();
getdeptList();
getUserList();
// 定义创建用户按钮事件
const userCreate = () => {
  action.value = 'add'
  showMadol.value = !showMadol.value;
};
// 定义弹窗取消事件
const handleCancel = () => {
  resetForm();
  showMadol.value = !showMadol.value;
};
// 定义提交事件
const handleSubmit = () => {
  dialogForm.value.validate(async (vaild) => {
    if (vaild) {
      // 发请求
      console.log(form);
      let data = toRaw(form)
      console.log(data);
      data.action = action.value
      // form 是响应式对象
      // data 是只需要一个普通的对象
      // 1. 需要把响应式对象变成普通对象
      let res = await api.userOperate(data)
      // 弹窗关闭
      showMadol.value = !showMadol.value
      // 重新发送获取用户列表请求,重新渲染数据
    }
  });
};

// 
// 重置表单事件
const resetForm = () => {
  dialogForm.value.resetFields()
}

// 定义编辑事件
const edit = (row) => {
  console.log(row);
  action.value = 'edit'
  showMadol.value = !showMadol.value
  nextTick(() => {
    Object.assign(form, row)
  })
}

// 删除用户信息
const delteUser = async (row) => {
  console.log(row);
  let data = {
    userIds: [row.userId]
  }
  let res = await api.userdelete(data)
  ElMessage({
    message: '删除成功',
    type: 'success',
  })
  getUserList()
}

let selection_data = ref([])
const handleSelectionChange = (data) => {
  selection_data.value = data
}

let requestuser_data = {
  userIds: []
}

// 批量删除信息
const deleteAll = async () => {
  selection_data.value.forEach(ele => {
    requestuser_data.userIds.push(ele.userId)
  })
  await api.userdelete(requestuser_data)
  getUserList()

}
// 重置样式
const resect = () => {
  user.userId = ''
  user.userName = ''
  user.state = ''
  getUserList()
}


// 查询状态
const onSubmit = async () => {
  getUserList()

}

</script>

<style lang="scss" scoped>
.query-form {
  height: 70px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}
.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>
